//
//  DYZRegistePagesController.m
//  DYZCars
//
//  Created by MF on 16/8/21.
//  Copyright © 2016年 MF. All rights reserved.
//

#import "DYZRegistePagesController.h"
#import "UILabel+Addition.h"
#import "UIButton+Addition.h"
#import "UIColor+Addition.h"
#import "DYZRegisteCheckController.h"
#import "DYZLoginUserInfo.h"
#import <SMS_SDK/SMSSDK.h>

#define kfilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]stringByAppendingPathComponent:@"usersInfo.data"]
@interface DYZRegistePagesController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong)NSMutableArray *userArray;

@property (nonatomic, weak)UITextField *nameField;

@property (nonatomic, weak)UITextField *psdTextFidle;

@property (nonatomic, weak)UITextField *testedTextFidle;

@property (nonatomic, weak)UIButton *textBtn;

@property (nonatomic, weak)UIButton *photoBtn;
//遵守协议
@property (nonatomic, weak)UIButton *protocolCheckbox;

//是否遵守协议的状态
@property (nonatomic, assign)BOOL  isStandProtocol;
@end

@implementation DYZRegistePagesController
//lazy loading


- (NSMutableArray *)userArray {
    if (!_userArray) {
        _userArray = [[NSMutableArray alloc] init];
    }
    return _userArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:0xebeefe];
    self.navigationItem.title = @"注册";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_backItem"] style:UIBarButtonItemStylePlain target:self action:@selector(backToLoginController)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem  alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(submitUser)];
    self.userArray = [NSKeyedUnarchiver unarchiveObjectWithFile:kfilePath];
    [self setupUI];
}

//返回登录界面
- (void)backToLoginController {
    [self.navigationController popViewControllerAnimated:true];
}
- (void)setupUI {
 
    
    //    账户名textfield
    UITextField *nameField = [[UITextField alloc] init];
    nameField.backgroundColor = [UIColor whiteColor];
    nameField.placeholder = @"请输入手机号";
    self.nameField = nameField;
    UIView *nameView = [[UIView alloc] init];
    nameView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:nameView];
    [nameView addSubview:nameField];
    //    验证码textfield
    UITextField *testedTextFidle = [[UITextField alloc] init];
    testedTextFidle.placeholder = @"请输入验证码";
    testedTextFidle.backgroundColor = [UIColor whiteColor];
    
    self.psdTextFidle = testedTextFidle;
    UIView *testedView = [[UIView alloc] init];
    testedView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:testedView];
    [testedView addSubview:testedTextFidle];
    //    密码textfield
    UITextField *psdTextFidle = [[UITextField alloc] init];
    psdTextFidle.placeholder = @"请输入新密码(6-12个字符)";
    psdTextFidle.backgroundColor = [UIColor whiteColor];
    psdTextFidle.secureTextEntry = YES;
    
    self.psdTextFidle = psdTextFidle;
    UIView *psdView = [[UIView alloc] init];
    psdView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:psdView];
    [psdView addSubview:psdTextFidle];
    //  获取验证码
    UIButton *textBtn = [UIButton buttonWithText:@"获取验证码" andTextColor:[UIColor whiteColor] backgroundColor:[UIColor colorWithHex:0x0073dd] andFontSize:17];
    self.textBtn = textBtn;
    [textBtn addTarget:self action:@selector(loadTextMessage) forControlEvents:UIControlEventTouchUpInside];
    [testedView addSubview:textBtn];
    
    
    UIButton *photoBtn = [UIButton buttonWithText:@"" andTextColor:[UIColor whiteColor] backgroundColor:[UIColor colorWithHex:0xebeefe] andFontSize:20];
    [photoBtn setImage:[UIImage imageNamed:@"zc_add"] forState:UIControlStateNormal];
    [photoBtn addTarget:self action:@selector(openSystemAlbum:) forControlEvents:UIControlEventTouchUpInside];
    self.photoBtn = photoBtn;
    [self.view addSubview:photoBtn];
    
    UIButton *photoBtn1 = [UIButton buttonWithText:@"" andTextColor:[UIColor whiteColor] backgroundColor:[UIColor colorWithHex:0xebeefe] andFontSize:20];
      [photoBtn1 setImage:[UIImage imageNamed:@"zc_add"] forState:UIControlStateNormal];
    [self.view addSubview:photoBtn1];
    
    
    //    条款按钮
    UILabel *protocalLabel = [UILabel labelWithText:@"我已阅读并同意《使用条款和隐私政策》" andTextColor:[UIColor blackColor] andFontSize:14];
    [self.view addSubview:protocalLabel];
    
    //    条款按钮勾选框
    UIButton *protocolCheckbox=[[UIButton alloc]initWithFrame:CGRectZero];
    [self.view addSubview:protocolCheckbox];
    self.protocolCheckbox = protocolCheckbox;
    [protocolCheckbox setBackgroundImage:[UIImage imageNamed:@"zc_unselect"] forState:UIControlStateNormal];
    
    [protocolCheckbox addTarget:self action:@selector(standProtocol:) forControlEvents:UIControlEventTouchUpInside];
    
    
    //    自动布局
    // 手机号
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(64);
        make.left.right.offset(0);
        make.height.offset(45);
    }];
    [nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(15);
        make.top.bottom.offset(0);
    }];
    //    验证码
    [testedView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(nameView.mas_bottom).offset(2);
        make.height.offset(45);
    }];
    [testedTextFidle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.width.offset(170);
        make.top.bottom.offset(0);
    }];
    [textBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.offset(0);
        make.width.offset(95);
    }];
    //    密码
    [psdView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.equalTo(testedView.mas_bottom).offset(2);
        make.height.offset(45);
    }];
    [psdTextFidle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(15);
        make.top.bottom.offset(0);
    }];
    
    //    上传图片
    [photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(psdTextFidle.mas_bottom).offset(23);
        make.left.offset(20);
        make.height.offset(94);
        make.width.offset(139);
    }];
    
    [photoBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(psdTextFidle.mas_bottom).offset(23);
        make.right.offset(-20);
        make.height.offset(94);
        make.width.offset(139);
    }];
    //    条款按钮
    [protocalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(photoBtn.mas_bottom).offset(16);
        make.centerX.equalTo(self.view);
    }];
    [protocolCheckbox mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(protocalLabel.mas_left).offset(-8);
        make.centerY.equalTo(protocalLabel);
        make.height.offset(30);
        make.width.offset(30);
    }];
}
//提交用户信息
- (void)submitUser {
    if (!self.isStandProtocol) {
        [self loginAlertWithTip:@"请确认您已遵守用户协议"];
        return;
    }
//    [SMSSDK commitVerificationCode:self.testedTextFidle.text phoneNumber:self.nameField.text zone:@"86" result:^(NSError *error) {
//        
//        if (!error) {
//            NSLog(@"验证成功");
//        }
//        else
//        {
//            NSLog(@"错误信息:%@",error);
//        }
//    }];
    
    NSLog(@"提交用户信息");
    if ([self.nameField.text isEqualToString:@""] || [self.psdTextFidle.text isEqualToString:@""]) {
        [self loginAlertWithTip:@"请输入正确的手机号"];
        return;
    }
    for (DYZLoginUserInfo *userInfo in self.userArray) {
        if ([userInfo.username isEqualToString:self.nameField.text]) {
            [self loginAlertWithTip:@"用户名已存在"];
        }
    }
    DYZLoginUserInfo *userinfo = [[DYZLoginUserInfo alloc] init];
    userinfo.username = self.nameField.text;
    userinfo.password = self.psdTextFidle.text;
    [self.userArray addObject:userinfo];
    [NSKeyedArchiver archiveRootObject:self.userArray toFile:kfilePath];
    DYZRegisteCheckController *vc = [[DYZRegisteCheckController alloc] init];
    [self.navigationController pushViewController:vc animated:true];
    
}


- (void)loginAlertWithTip:(NSString *)tip {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:tip preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:true completion:nil];
}
- (void)standProtocol:(UIButton *)sender {
    if (self.isStandProtocol) {
        [self.protocolCheckbox setBackgroundImage:[UIImage imageNamed:@"zc_unselect"] forState:UIControlStateNormal];
        self.isStandProtocol = false;
    } else {
        [self.protocolCheckbox setBackgroundImage:[UIImage imageNamed:@"zc_select"] forState:UIControlStateNormal];
        self.isStandProtocol = true;
    }
}
//获取验证码
- (void)loadTextMessage {
    [self performSelectorInBackground:@selector(time) withObject:nil];
}
- (void)time {
    self.textBtn.enabled = false;
    
//    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.nameField.text
//                                   zone:@"86"
//                       customIdentifier:nil
//                                 result:^(NSError *error){
//                                     if (!error) {
//                                         NSLog(@"获取验证码成功");
//                                     } else {
//                                         NSLog(@"错误信息：%@",error);
//                                     }
//                                 }];
    int second = 60;
    for (int i = 0; i < second; i++) {
        [NSThread sleepForTimeInterval:1];
        NSString *title = [NSString stringWithFormat:@"%zd秒",second - 1 - i];
        
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [self.textBtn setTitle:title forState:UIControlStateNormal];
        }];
        
        if (i == second - 1) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.textBtn.enabled = true;
                [self.textBtn setTitle:@"获取" forState:UIControlStateNormal];
                return ;
            }];
        }
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

//打开系统相册
- (void)openSystemAlbum:(UIButton *)sender {
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - 协议方法的实现
//协议方法，选择完毕以后，呈现在imageShow里面
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //    NSLog(@%@,info);  //UIImagePickerControllerMediaType,UIImagePickerControllerOriginalImage,UIImagePickerControllerReferenceURL
    NSString *mediaType = info[@"UIImagePickerControllerMediaType"];
    if ([mediaType isEqualToString:@"public.image"]) {  //判断是否为图片
        
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.photoBtn setBackgroundImage:image forState:UIControlStateNormal];
        
        //通过判断picker的sourceType，如果是拍照则保存到相册去
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    //  else  当然可能是视频，这里不作讨论~方法是类似的~
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//此方法就在UIImageWriteToSavedPhotosAlbum的上方
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSLog(@"已保存");
}

@end
